@<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="15">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="userInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="userList" style="width: 100%">
        <el-table-column type="index"></el-table-column>

        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <!-- 渲染成滑块开关组件 -->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChanged(scope.row)"
            />
          </template>
        </el-table-column>

        <!-- 渲染操作选项 -->
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editUser(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deletUser(scope.row.id)" />
            <!-- 角色分配按钮 -->
            <el-tooltip
              effect="dark"
              content="角色分配"
              placement="top"
              :enterable="false"
              
            >
              <el-button type="danger" icon="el-icon-setting"
               size="mini"  @click="setRoles(scope.row)"/>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="userInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="userInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible" 
      width="50%"
      @close="dialogClosed"
      
       >
      <el-form ref="newUserRef" :model="newUser" label-width="80px" :rules="addUserRules">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="newUser.username" ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="newUser.password"></el-input>
        </el-form-item >
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="newUser.email" ></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="newUser.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 修改用户对话框 -->
    <el-dialog
  title="修改用户"
  :visible.sync="editDialogVisible"
  width="50%"
  >
  <!-- 用户名 -->
  <el-form ref="userDataRef" :model="userData" label-width="80px" :rules="editUserRules">
    <el-form-item label="用户名">
      <el-input v-model="userData.username" disabled value="userData.username"></el-input>
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="userData.email"  value="userData.email"></el-input>
    </el-form-item>
    <el-form-item label="手机" prop="mobile">
      <el-input v-model="userData.mobile" value="userData.mobile"></el-input>
    </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="editClosed">取 消</el-button>
    <el-button type="primary" @click="toEditUser">确 定</el-button>
  </span>
</el-dialog>

<!-- 分配角色的对话框 -->
<el-dialog  @close="resetData" title="分配角色" 
:visible.sync="setRoleDialogVisible" width="50%">
  <p>当前的用户:{{userData.username}}</p>
  <p>当前的角色:{{userData.role_name}}</p>
  <p>分配角色: 

      <!-- 渲染下拉角色列表 -->
      <el-select v-model="selectedRoleId" placeholder="请选择">
    <el-option 
      v-for="item in rolesList"
      :key="item.id"
      :label="item.roleName"
      :value="item.id">
    </el-option>
  </el-select>
  </p>
<span slot="footer" class="dialog-footer">
  <el-button @click="setRoleDialogVisible=false">取消</el-button>
  <el-button type="primary" @click="saveRoleData">确定</el-button>
</span>
</el-dialog>
  </div>
</template>

<script>
import { debounce } from "../../../utils/Tools";
export default {
  data() {
    //  //自定义邮箱验证规则
    var checkmail =(rule, value, callback) => {
      const regMail = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,5}$/
      if(regMail.test(value)){
        return callback()
      }
      return callback(new Error('请输入正确的邮箱'))
    }

      //自定义手机验证规则
    var checktel =(rule, value, callback) => {
      const regTel = /^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/
      if(regTel.test(value)) {
        return callback()
      }
      return callback(new Error('请输入正确的手机号'))
    }


    return {
      // 用户列表
      userList: [],

      // 是否显示编辑用户对话框
      editDialogVisible: false,
      //是否显示角色分配对话框
      setRoleDialogVisible: false,
      // 角色列表数据
      rolesList: [],
      // 保存用户数据
      userData:{},

      // 分配角色中已选中的角色的id
      selectedRoleId: '',

      //总页数
      total: 0,

      // 请求参数
      userInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      // 修改用户状态
      changeState: {
        uid: 0,
        type: "",
      },
      addDialogVisible: false,
      // 添加用户的规则
      addUserRules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min:3, max: 10, message: '长度在3到10位之间', trigger: 'blur'}
        ],
         password:[
                {required: true, message:'请输入密码', trigger:'blur'},
                {min:6, max: 16, message: '长度在6到16位之间', trigger: 'blur'}
            ],
            email: [
                {required: true, message:'请输入邮箱', trigger:'blur'},
               {validator: checkmail, trigger: 'blur'}

            ],
            mobile: [
              {required: true, message:'请输入手机号', trigger:'blur'},
              {validator: checktel, trigger: 'blur'}
            ]

      },
      
      // 添加用户的数据
      newUser: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      editUserRules: {
         email: [
          {required: true, message: "请输入邮箱", trigger: 'blur'},
          {validator: checkmail, trigger: 'blur'}
        ],
        mobile: [
           {required: true, message:'请输入手机号', trigger:'blur'},
              {validator: checktel, trigger: 'blur'}
        ]
      },
     
    
    }
  },
  created() {
    this.getUserList();
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.userInfo,
      });
      console.log(this.userList)
      this.userList = res.data.users;
      this.total = res.data.total;
    },
    // 每页显示条数
    handleSizeChange(pagesize) {
      this.userInfo.pagesize = pagesize;
      this.getUserList();
    },
    // 当前页码
    handleCurrentChange(newPage) {
      this.userInfo.pagenum = newPage;
      this.getUserList();
    },

    // 监听用户状态的改变
    async userStateChanged(userInfo) {
      const { id, mg_state } = userInfo;

      const { data: res } = await this.$http.put(
        `users/${id}/state/${mg_state}`
      );
      if (res.meta.status != 200) {
        userInfo.mg_state = !userInfo.mg_state;
        return this.$message.error("用户状态更新失败");
      }
      this.$message.success("用户状态刚更新成功");
    },
    // 重置表单
    dialogClosed() {
      this.$refs.newUserRef.resetFields()
    },
    // 表单预验证,添加用户
    async addUser() {

      this.$refs.newUserRef.validate( res => {
        if(!res) return 
      })
    //验证通过,发起添加用户请求
      const { data: res } = await this.$http.post('users',this.newUser)
      if(res.meta.status != 201) {

        return this.$message.error("用户添加失败")

      }
      this.addDialogVisible = false
      this.getUserList()
      return this.$message.success("用户添加成功")

    },
    // 获取修改用户信息
    async editUser(id) {
     
      const {data: res} = await this.$http.get(`users/${id}`);
      console.log(res)
      if(res.meta.status != 200) return 
      
      this.userData = res.data
    

       this.editDialogVisible = true
      

    },
    // 编辑用户
     toEditUser() {
      //表单验证
      this.$refs.userDataRef.validate(async result => {
        if(!result) return 

          //开始发送修改请求
      const { id, email, mobile } = this.userData
      const {data: res} = await this.$http.put(`users/${id}`,{email, mobile})
      if(res.meta.status != 200) return this.$message.error("数据修改失败")

      this.$message.success("修改成功");
      this.editDialogVisible = false;
      this.getUserList()

      })
    

      
    },
    //删除用户
    async deletUser(id) {
      const result = await this.$confirm('是否确认永久删除该用户?',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if(result != 'confirm') return 

      //开始发送网路请求
      const { data: res } = await this.$http.delete(`users/${id}`)
      if(res.meta.status != 200) return this.$message.error('删除失败')
      this.$message.success('删除成功')
      this.getUserList()

    },
    // 重置修改表单
    editClosed() {
      this.$refs.userDataRef.resetFields();
      this.editDialogVisible = false;
    },
    // 角色分配权限
    async setRoles(role) {
      this.userData = role

      // 获取所有角色列表
      const {data: res } = await this.$http.get('roles')
      if(res.meta.status != 200) {
        return this.$message.error("获取角色列表失败")
      }
      
      // 保存角色数据
      this.rolesList = res.data

      this.setRoleDialogVisible = true

    },

    // 提交分配角色
    async saveRoleData() {
      // 验证用户是否选择
      if(!this.selectedRoleId) {
        this.$message.error("请选择角色")
      }

      // 发起分配角色的请求
      const {data: res } = await this.$http.put(`users/${this.userData.id}/role`,
      {rid:this.selectedRoleId})
      console.log(res)
      if(res.meta.status != 200) {
        return this.$message.error("角色分配失败")
      }
      this.$message.success("角色分配成功")
      this.getUserList()

      this.setRoleDialogVisible = false

    
    },
    // 重置对话框数据
    resetData() {
        // 重置对象
      this.userData = {}
      // 重置id
      this.selectedRoleId = ''
    }


   
  },
};
</script>

<style>
</style>